﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XbsWebAPI.Application.SystemAdmin.Dtos;
using XbsWebAPI.Core.Repositories;
using XbsWebAPI.Core.Repositories.SystemAdmin;

namespace XbsWebAPI.Application.SystemAdmin
{
    public class XbsAdminUserAppService: IXbsAdminUserAppService
    {
        private readonly IXbsAdminUserRepository _xbsAdminUserRepository;
        private readonly ISystemRoleRepository _systemRoleRepository;
        private readonly ILogger<XbsAdminUserAppService> _logger;
        private readonly IMapper _mapper;


        public XbsAdminUserAppService(IXbsAdminUserRepository xbsAdminUserRepository, ISystemRoleRepository systemRoleRepository, ILogger<XbsAdminUserAppService> logger,IMapper mapper)
        {
            _xbsAdminUserRepository = xbsAdminUserRepository;
            _systemRoleRepository = systemRoleRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public ResultDto<List<ListAdminUserDto>> FindAdminUsers()
        {
            var result = new ResultDto<List<ListAdminUserDto>>();
            try
            {
                var adminUsers = _xbsAdminUserRepository.AsQueryable().ToList();
                var list = _mapper.Map<List<ListAdminUserDto>>(adminUsers);
                var roles = _systemRoleRepository.AsQueryable().ToList();
                foreach (var item in list)
                {
                    item.RoleName = roles.FirstOrDefault(a => a.Id == item.RoleId)?.Name;
                }
                result.Result = list;
                return result;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                _logger.LogError("FindAdminUsers:" + e.Message);
                return result;
            }


            return result;
        }
    }
}
